package com.eastrobot.report.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BaseController extends HttpServlet {

	private static final long serialVersionUID = -1301171098203450232L;
	public final static String redirPath = "redirect:";

	protected String redirPath(String path) {
		return redirPath + path;
	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			String method = req.getParameter("method");
			Method m = this.getClass().getMethod(method, HttpServletRequest.class,
					HttpServletResponse.class);
			String path = (String) m.invoke(this, req, resp);
			if (path != null && !"".equals(path)) {
				if (path.startsWith(redirPath)) {
					String rp = path.substring(redirPath.length());
					resp.sendRedirect(rp);
				} else {
					req.getRequestDispatcher("/WEB-INF/" + path).forward(req, resp);
				}
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}

	// 输出结果集
	protected void writeJson(HttpServletResponse response, String result) 
				throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.write(result);
		out.flush();
		out.close();
	}

}
